﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "新增产品信息";
}
<link href="~/css/site.css" rel="stylesheet" />
<link href="~/layui/css/layui.css" rel="stylesheet" />

<script src="~/layui/layui.js"></script>
<script src="~/js/site.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">新增产品信息</h3>
                    <div class="card-tools">
                        <a href="/Home/GetProductItem" class="btn btn-secondary btn-sm">
                            <i class="layui-icon layui-icon-return"></i> 返回列表
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    <form id="addProductForm">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="productName" class="form-label">产品名称 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="productName" name="productName" 
                                           placeholder="请输入产品名称" required>
                                    <div class="invalid-feedback">
                                        请输入产品名称
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="productCode" class="form-label">产品编码 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="productCode" name="productCode" 
                                           placeholder="请输入产品编码" required>
                                    <div class="invalid-feedback">
                                        请输入产品编码
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="specification" class="form-label">规格 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="specification" name="specification" 
                                           placeholder="请输入产品规格" required>
                                    <div class="invalid-feedback">
                                        请输入产品规格
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="unitName" class="form-label">单位名称 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="unitName" name="unitName" 
                                           placeholder="请输入单位名称" required>
                                    <div class="invalid-feedback">
                                        请输入单位名称
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="classify" class="form-label">分类 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="classify" name="classify" 
                                           placeholder="请输入产品分类" required>
                                    <div class="invalid-feedback">
                                        请输入产品分类
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="planNum" class="form-label">计划数量 <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="planNum" name="planNum" 
                                           placeholder="请输入计划数量" required min="1">
                                    <div class="invalid-feedback">
                                        请输入有效的计划数量
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="planStart" class="form-label">计划开始时间 <span class="text-danger">*</span></label>
                                    <input type="datetime-local" class="form-control" id="planStart" name="planStart" 
                                           required>
                                    <div class="invalid-feedback">
                                        请选择计划开始时间
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="planEnd" class="form-label">计划结束时间 <span class="text-danger">*</span></label>
                                    <input type="datetime-local" class="form-control" id="planEnd" name="planEnd" 
                                           required>
                                    <div class="invalid-feedback">
                                        请选择计划结束时间
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row mt-4">
                            <div class="col-12">
                                <div class="form-group text-center">
                                    <button type="submit" class="btn btn-primary" id="btnSubmit">
                                        <i class="layui-icon layui-icon-ok"></i> 提交
                                    </button>
                                    <button type="button" class="btn btn-secondary ml-2" id="btnReset">
                                        <i class="layui-icon layui-icon-refresh"></i> 重置
                                    </button>
                                    <a href="/Home/GetProductItem" class="btn btn-outline-secondary ml-2">
                                        <i class="layui-icon layui-icon-close"></i> 取消
                                    </a>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {
        // 设置默认时间为当前时间
        const now = new Date();
        const localDateTime = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
        $('#planStart').val(localDateTime);
        
        // 设置结束时间为开始时间后1小时
        const endTime = new Date(now.getTime() + 60 * 60 * 1000);
        const endDateTime = new Date(endTime.getTime() - endTime.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
        $('#planEnd').val(endDateTime);

        // 表单提交事件
        $('#addProductForm').on('submit', function (e) {
            e.preventDefault();
            submitForm();
        });

        // 重置按钮事件
        $('#btnReset').click(function () {
            resetForm();
        });

        // 计划开始时间变化事件
        $('#planStart').change(function () {
            const startTime = new Date($(this).val());
            const endTime = new Date(startTime.getTime() + 60 * 60 * 1000); // 默认结束时间为开始时间后1小时
            const endDateTime = new Date(endTime.getTime() - endTime.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
            $('#planEnd').val(endDateTime);
        });

        // 提交表单
        function submitForm() {
            // 验证表单
            if (!validateForm()) {
                return;
            }

            // 验证时间逻辑
            if (!validateTimeLogic()) {
                return;
            }

            // 显示加载状态
            showLoading();

            // 收集表单数据
            const formData = {
                productName: $('#productName').val().trim(),
                productCode: $('#productCode').val().trim(),
                specification: $('#specification').val().trim(),
                unitName: $('#unitName').val().trim(),
                classify: $('#classify').val().trim(),
                planStart: $('#planStart').val() + ':00.000Z', // 转换为ISO格式
                planEnd: $('#planEnd').val() + ':00.000Z', // 转换为ISO格式
                planNum: parseInt($('#planNum').val())
            };

            // 调用后端API
            $.ajax({
                url: 'http://localhost:5025/api/Production/AddProduction',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function (response) {
                    hideLoading();
                    if (response.code === 200) {
                        showSuccess('添加产品信息成功！');
                       
                    } else {
                        showError('添加失败：' + response.msg);
                    }
                },
                error: function (xhr, status, error) {
                    hideLoading();
                    let errorMsg = '请求失败';
                    if (xhr.responseJSON && xhr.responseJSON.msg) {
                        errorMsg += '：' + xhr.responseJSON.msg;
                    } else {
                        errorMsg += '：' + error;
                    }
                    showError(errorMsg);
                }
            });
        }

        // 验证表单
        function validateForm() {
            let isValid = true;
            const requiredFields = [
                'productName',
                'productCode', 
                'specification',
                'unitName',
                'classify',
                'planStart',
                'planEnd',
                'planNum'
            ];

            // 清除之前的验证状态
            $('.form-control').removeClass('is-invalid');

            // 验证必填字段
            requiredFields.forEach(function (fieldName) {
                const field = $('#' + fieldName);
                const value = field.val().trim();
                
                if (!value) {
                    field.addClass('is-invalid');
                    isValid = false;
                } else {
                    field.addClass('is-valid');
                }
            });

            // 验证数字字段
            const planNum = parseInt($('#planNum').val());
            if (isNaN(planNum) || planNum <= 0) {
                $('#planNum').addClass('is-invalid');
                isValid = false;
            }

            return isValid;
        }

        // 验证时间逻辑
        function validateTimeLogic() {
            const planStart = new Date($('#planStart').val());
            const planEnd = new Date($('#planEnd').val());
            
            if (planEnd <= planStart) {
                showError('计划结束时间必须晚于计划开始时间');
                $('#planEnd').addClass('is-invalid');
                return false;
            }
            
            return true;
        }

        // 重置表单
        function resetForm() {
            $('#addProductForm')[0].reset();
            $('.form-control').removeClass('is-invalid is-valid');
            
            // 重新设置默认时间
            const now = new Date();
            const localDateTime = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
            $('#planStart').val(localDateTime);
            
            const endTime = new Date(now.getTime() + 60 * 60 * 1000);
            const endDateTime = new Date(endTime.getTime() - endTime.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
            $('#planEnd').val(endDateTime);
        }

        // 显示加载状态
        function showLoading() {
            $('#btnSubmit').prop('disabled', true).html('<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i> 提交中...');
        }

        // 隐藏加载状态
        function hideLoading() {
            $('#btnSubmit').prop('disabled', false).html('<i class="layui-icon layui-icon-ok"></i> 提交');
        }

        // 显示成功消息
        function showSuccess(message) {
            layer.msg(message, {
                icon: 1,
                time: 2000
            });
        }

        // 显示错误消息
        function showError(message) {
            layer.msg(message, {
                icon: 2,
                time: 3000
            });
        }

        // 实时验证
        $('.form-control').on('blur', function () {
            const field = $(this);
            const value = field.val().trim();
            
            if (field.attr('required') && !value) {
                field.addClass('is-invalid');
            } else {
                field.removeClass('is-invalid').addClass('is-valid');
            }
        });
    });
</script>

<style>
    .card {
        margin: 20px;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    }
    
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #f8f9fa;
        border-bottom: 1px solid #dee2e6;
    }
    
    .form-label {
        font-weight: 500;
        margin-bottom: 0.5rem;
    }
    
    .form-control:focus {
        border-color: #80bdff;
        box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
    }
    
    .is-valid {
        border-color: #28a745;
    }
    
    .is-invalid {
        border-color: #dc3545;
    }
    
    .btn {
        padding: 0.375rem 0.75rem;
        font-size: 1rem;
        line-height: 1.5;
        border-radius: 0.25rem;
    }
    
    .btn:disabled {
        opacity: 0.65;
        cursor: not-allowed;
    }
    
    .layui-icon {
        font-size: 14px;
        margin-right: 4px;
    }
    
    .text-danger {
        color: #dc3545 !important;
    }
    
    .form-group {
        margin-bottom: 1rem;
    }
    
    .card-tools {
        display: flex;
        align-items: center;
    }
</style>